var HOST_URI = 'http://api.frp.linkfun.top/applet/';
// var HOST_URI = 'https://boot.api.linkfun.top/applet/';
// var HOST_URI = 'https://m1-spring.nats.raychow.win/applet/';
var version = "wxapp_v1.0.0";

var app = getApp();
//字符串拼接成为url
function obj2uri (obj) {
    return Object.keys(obj).map(function (k) {
        return encodeURIComponent(k) + '=' + encodeURIComponent(obj[k]);
    }).join('&');
}

//http fetch
function basePost (api,obj,succeedCallBack,failCallBack){  
  if (typeof obj != "object" ){
      obj = {};
  }
  //obj.uid = app.globalData.uid;
  obj.timeStamp =  Date.parse(new Date());
  var commen = {};
  commen.version = version;
  var url = HOST_URI + api + "?" + obj2uri(commen);
  //发送数据
  fetch( url, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(obj)
    })
    .then(function(res) {
        if (res.ok) {
            res.json().then(function(data) {
                if( typeof succeedCallBack == "function"){
                    succeedCallBack(data);
                }                
            });
        } 
        else {
            if( typeof failCallBack == "function"){
                failCallBack();
            }
        }
    }, function(e) {
        if( typeof failCallBack == "function"){
                failCallBack();
            }
    });
}

function baseGet(api, obj, succeedCallBack, failCallBack) {
  if (obj == null){
    obj = {};
  }
  obj.version = version;
  var url = HOST_URI + api + "?" + obj2uri(obj);
  wx.request({
    url: url,
    //data: null,
    method: 'get',
    header: { 'Content-Type': 'application/json' },
    success: function (res) {
      return typeof succeedCallBack == "function" && succeedCallBack(res.data)
    },
    fail: function () {
      return typeof failCallBack == "function" && failCallBack(false)
    }
  })
}



module.exports = {  
  getNews: function (callback){
      var obj = {};
      baseGet("v1/news", obj, function (resObj) { callback(resObj) }, null);

    },
  getDetails: function (sid, callback){
    var obj = {};
    obj.sid = sid;
    baseGet("v1/details", obj, function (resObj) { callback(resObj) }, null);
  },
};
